package net.xgclass.online_xgclass.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import net.xgclass.online_xgclass.config.CacheKeyManager;
import net.xgclass.online_xgclass.model.entity.Chapter;
import net.xgclass.online_xgclass.model.entity.Episode;
import net.xgclass.online_xgclass.model.entity.Video;
import net.xgclass.online_xgclass.model.entity.VideoBanner;
import net.xgclass.online_xgclass.mapper.VideoMapper;
import net.xgclass.online_xgclass.service.VideoService;
import net.xgclass.online_xgclass.utils.BaseCache;
import net.xgclass.online_xgclass.utils.UploadFileImgUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;
import java.util.UUID;


@Service
public class VideoServiceImpl implements VideoService {

    @Autowired
    private VideoMapper videoMapper;


    @Autowired
    private BaseCache baseCache;


    @Override
    public List<Video> listVideo() {


        try{

          Object cacheObj =  baseCache.getTenMinuteCache().get(CacheKeyManager.INDEX_VIDEL_LIST,()->{

                List<Video> videoList = videoMapper.listVideo();

                return videoList;

            });

          if(cacheObj instanceof List){
              List<Video> videoList = (List<Video>)cacheObj;
              return videoList;
          }

        }catch (Exception e){
            e.printStackTrace();
        }


        return null;
    }



    @Override
    public List<VideoBanner> listBanner() {

        try{

            Object cacheObj =  baseCache.getTenMinuteCache().get(CacheKeyManager.INDEX_BANNER_KEY, ()->{

                List<VideoBanner> bannerList =  videoMapper.listVideoBanner();

                System.out.println("从数据库里面找轮播图列表");

                return bannerList;

            });

            if(cacheObj instanceof List){
                List<VideoBanner> bannerList = (List<VideoBanner>)cacheObj;
                return bannerList;
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }




    @Override
    public Video findDetailById(int videoId) {

        //单独构建一个缓存key，每个视频的key是不一样的
        String videoCacheKey = String.format(CacheKeyManager.VIDEO_DETAIL,videoId);

        try{

         Object cacheObject = baseCache.getOneHourCache().get( videoCacheKey, ()->{

                // 需要使用mybaits关联复杂查询
                Video video = videoMapper.findDetailById(videoId);

                return video;

            });

         if(cacheObject instanceof Video){

             Video video = (Video)cacheObject;
             return video;
         }

        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public List<Video> listVideoDetail() {
        return videoMapper.listVideoDetail();
    }

    @Override
    public List<Video> videoPageInfo(int pagenum, int pagesize) {
        return videoMapper.videoPageInfo(pagenum,pagesize);
    }

    /**
     * oss上传图片
     * @param file
     * @return
     */
    @Override
    public String uploadFileImg(MultipartFile file) {{
        // 工具类获取值
        String endpoint = UploadFileImgUtils.END_POIND;
        String accessKeyId = UploadFileImgUtils.ACCESS_KEY_ID;
        String accessKeySecret = UploadFileImgUtils.ACCESS_KEY_SECRET;
        String bucketName = UploadFileImgUtils.BUCKET_NAME;

        try {
            // 创建OSS实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            //获取上传文件输入流
            InputStream inputStream = file.getInputStream();
            //获取文件名称
            String fileName = "xgclass-img/"+file.getOriginalFilename();

            //调用oss方法实现上传
            //第一个参数  Bucket名称
            //第二个参数  上传到oss文件路径和文件名称   aa/bb/1.jpg
            //第三个参数  上传文件输入流
            ossClient.putObject(bucketName,fileName , inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();

            //把上传之后文件路径返回
            //需要把上传到阿里云oss路径手动拼接出来
            //  https://edu-guli-1010.oss-cn-beijing.aliyuncs.com/01.jpg
            String url = "https://"+bucketName+"."+endpoint+"/"+fileName;
            return url;
        }catch(Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

    @Override
    public int addVideo(Video video) {

        int flag = videoMapper.addVideo(video);
        Video queryVideo = videoMapper.queryVideo();

        if (flag==1){
            Integer id = queryVideo.getId();
            System.out.println(id+"=======================");
            return id;
        }else {
            return 0;
        }
    }

    @Override
    public List<Chapter> queryChaEpiByVideoId(Integer videoId) {
        return videoMapper.queryChaEpiByVideoId(videoId);
    }

    /**
     * 上传视频 阿里云点播
     * @param file
     * @return
     */
    @Override
    public String uploadVideo(MultipartFile file) {
        try {
            //accessKeyId, accessKeySecret
            //fileName：上传文件原始名称
            // 01.03.09.mp4
            String fileName = file.getOriginalFilename();
            //title：上传之后显示名称
            String title = fileName.substring(0, fileName.lastIndexOf("."));
            //inputStream：上传文件输入流
            InputStream inputStream = file.getInputStream();
            System.out.println(UploadFileImgUtils.ACCESS_KEY_ID);
            System.out.println(UploadFileImgUtils.ACCESS_KEY_SECRET);
            UploadStreamRequest request = new UploadStreamRequest(UploadFileImgUtils.ACCESS_KEY_ID,UploadFileImgUtils.ACCESS_KEY_SECRET, title, fileName, inputStream);

            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);

            String videoId = null;
            if (response.isSuccess()) {
                videoId = response.getVideoId();

            } else { //如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因
                videoId = response.getVideoId();
            }
            return videoId;
        }catch(Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    @Override
    public int addChapter(Chapter chapter) {
        return videoMapper.addChapter(chapter);
    }

    @Override
    public int addEpisode(Episode episode) {
        return videoMapper.addEpisode(episode);
    }

    @Override
    public List<VideoBanner> videoBannerPageInfo(int pagenum, int pagesize) {
        return videoMapper.videoBannerPageInfo(pagenum,pagesize);
    }

    @Override
    public int editCourse(Video video) {
        return videoMapper.editCourse(video);
    }

    @Override
    public int removeCourse(Integer id) {
        return videoMapper.removeCourse(id);
    }

    @Override
    public int removeChapter(Integer id) {
        return videoMapper.removeChapter(id);
    }

    @Override
    public int removeEpisode(Integer id) {
        return videoMapper.removeEpisode(id);
    }

    @Override
    public int editChapter(Chapter chapter) {
        return videoMapper.editChapter(chapter);
    }

    @Override
    public int removeEpisodeByChapterId(Integer id) {
        return videoMapper.removeEpisodeByChapterId(id);
    }

    @Override
    public int removeChapterByChapterId(Integer id) {
        return videoMapper.removeChapterByChapterId(id);
    }

    @Override
    public int removeEpisodeByEpisodeId(Integer id) {
        return videoMapper.removeEpisodeByEpisodeId(id);
    }

    @Override
    public int editEpisode(Episode episode) {
        return videoMapper.editEpisode(episode);
    }

    @Override
    public int addBanner(VideoBanner videoBanner) {
        return videoMapper.addBanner(videoBanner);
    }

    @Override
    public int editBanner(VideoBanner videoBanner) {
        return videoMapper.editBanner(videoBanner);
    }

    @Override
    public int removeBanner(Integer id) {
        return videoMapper.removeBanner(id);
    }
}
